import Datastore from "nedb-promises"
import {
  SelectDatabase,
} from '@/utils/db/OperateDatabase'
import {
  SearchDataSync
} from '@/utils/db/search'
import {
  customizeDictionaryDB,
  type CustomizeDictionaryValueType
} from '@/routes/bug-manager/customizeDictionaryDB'

/**
 * 获取字典值
 */
const GetDictionaryItemName = async (dictionaryValue: string, dictionaryItemValue: string) => {
  // 不用大写的问题暴露出来了
  const db = SelectDatabase('bug-manager', 'system', 'Dictionary')

  let dictionaryItemName = ''

  await db.find({ dictionaryValue, _del: false }).then(async (res: any) => {
    const dictionaryArray = res[0]?.dictionaryArray || []
    if (dictionaryArray.length > 0) {
      for (let i = 0; i < dictionaryArray.length; i++) {
        if (dictionaryItemValue == dictionaryArray[i].value) {
          dictionaryItemName = dictionaryArray[i].name
          break
        }
      }
    }
  })

  return dictionaryItemName
}

/**
 * 获取字典数组
 * @param dictionaryValue 字典值
 * @returns 字典数组
 */
const GetDictionaryArrayByValue = async (dictionaryValue: string, isCustom = false) => {
  if (!isCustom) {
    const db = SelectDatabase('bug-manager', 'system', 'Dictionary')
    let result: any[] = []
    await db.find({ dictionaryValue, _del: false }).then((res: any) => {
      result = res[0]?.dictionaryArray || []
    })
    return result
  } else {
    const db = SelectDatabase('bug-manager', customizeDictionaryDB[dictionaryValue as CustomizeDictionaryValueType].module, dictionaryValue)
    let result: any[] = []
    await db.find({ _del: false }).then((res: any) => {
      result = res
    })
    return result
  }
}

/**
 * 从已有数据中获取字典名称
 * @param value
 * @param dictionaryArray
 * @returns
 */
const GetDictionaryItemNameByArray = (value: string, dictionaryArray: any[]) => {
  let dictionaryItemName = ''
  for (let i = 0; i < dictionaryArray.length; i++) {
    if (dictionaryArray[i].value == value) {
      dictionaryItemName = dictionaryArray[i].label
      break
    }
  }
  return dictionaryItemName || value
}

/**
 * 从自定义字典中获取字典名称
 */
const GetCustomizeDictionaryItemNameByArray = (dictionaryItem: DictionaryItem, dictionaryArray: any[], nameKey: string, valueKey: string) => {
  let dictionaryItemName = ''
  if (!dictionaryItem) {
    return dictionaryItemName
  }
  for (let i = 0; i < dictionaryArray.length; i++) {
    if (dictionaryArray[i][valueKey] == dictionaryItem.value) {
      dictionaryItemName = dictionaryArray[i][nameKey]
      break
    }
  }
  return dictionaryItemName
}

export {
  GetDictionaryItemName,
  GetDictionaryItemNameByArray,
  GetCustomizeDictionaryItemNameByArray,
  GetDictionaryArrayByValue,
}
